package com.oa.erp.ass.service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.erp.ass.entity.AssetCard;
import com.oa.erp.ass.entity.AssetCardOper;
import com.oa.erp.ass.entity.AssetDetail;
import com.oa.erp.ass.entity.AssetInventoryTaskDetail;
import com.oa.erp.ass.enums.AssetMngEnum;
import com.oa.erp.ass.enums.AssetStatusEnum;
import com.oa.erp.ass.enums.MngStatus;
import com.oa.erp.ass.enums.TaskDetailEnum;
import com.oa.erp.ass.listener.AssetCardImportExcelListener;
import com.oa.erp.ass.mapper.AssetCardMapper;
import com.oa.erp.ass.vo.AssetCardExcelVo;
import com.oa.erp.ass.vo.AssetDetailVo;
import com.oa.erp.stk.service.WarehouseService;
import com.oa.hr.user.service.SysUserService;
import com.oa.kq.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class AssetCardService extends BaseService<AssetCardMapper,AssetCard> {
	static Logger logger =LoggerFactory.getLogger(AssetCardService.class);

	/**
	 * 自定义查询，支持多表关联
	 * @param page 分页条件
	 * @param ew 一定要，并且必须加@Param("ew")注解
	 * @param ext 如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
	 * @return
	 */
	public List<Map<String,Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String,Object> ext){
		return baseMapper.selectListMapByWhere(page,ew,ext);
	}

	@Lazy
	@Autowired
	private AssetDetailService assetDetailService;

	@Autowired
	private AssetInventoryTaskDetailService assetInventoryTaskDetailService;

	@Autowired
	private AssetCardOperService assetCardOperService;

	@Autowired
	private WarehouseService warehouseService;

	@Autowired
	private AssetCategoryService assetCategoryService;

	@Autowired
	private DeptService deptService;

	@Autowired
	private SysUserService sysUserService;



	@Transactional
	public void updateCardStatus(List<AssetDetailVo> detailVoList, String assetStatus) {
		User user = LoginUtils.getCurrentUserInfo();
		List<AssetCard> assetCards = new ArrayList<>();
		for(AssetDetailVo assetDetailVo : detailVoList) {
			AssetCard assetCard = new AssetCard();
			BeanUtils.copyProperties(assetDetailVo, assetCard);
			assetCard.setLastEditUserid (user.getUserid());
			assetCard.setLastEditTime(new Date());
			assetCard.setLastEditUsername(user.getUsername());

			//更新卡片最新的责任人，仓库地址，使用部门
			assetCard.setDeptid(assetDetailVo.getNowDeptid());
			assetCard.setDeptName(assetDetailVo.getNowDeptName());
			assetCard.setStoreAddress(assetDetailVo.getNowStoreAddress());
			assetCard.setWarehouseId(assetDetailVo.getNowWarehouseId());
			assetCard.setWarehouseName(assetDetailVo.getNowWarehouseName());
			assetCard.setPersonLiableUserid(assetDetailVo.getNowPsersonLiableUserid());
			assetCard.setPersonLiableUsername(assetDetailVo.getNowPsersonLiableUsername());

			if(!assetStatus.equals(AssetMngEnum.CHANGE.getStatus()) && !assetStatus.equals(AssetMngEnum.INVENTORY.getStatus())) {
				assetCard.setCardStatus(assetStatus);
			}

			assetCards.add(assetCard);
		}
		this.batchUpdate(assetCards);
	}


	/**
	 * 添加资产卡片
	 * @param assetCard
	 */
	@Transactional
	public void insertAssetCard(AssetCard assetCard) {
		//1.资产编码是否存在
		AssetCard ac = new AssetCard();
		ac.setAssetSn(assetCard.getAssetSn());
		if(this.countByWhere(ac)>0) {
			throw new BizException("资产编码不能重复");
		}

		//3.添加资产卡片
		User user = LoginUtils.getCurrentUserInfo();
		assetCard.setCreateUserid(user.getUserid());
		assetCard.setCreateUsername(user.getUsername());
		assetCard.setCreateTime(new Date());
		assetCard.setLastEditUserid(user.getUserid());
		assetCard.setLastEditUsername(user.getUsername());
		assetCard.setLastEditTime(new Date());
		assetCard.setIsInventory("0");
		this.insert(assetCard);


		//4.如果是带有盘点任务的卡片信息,则需要做其他操作。
		if(!StringUtils.isEmpty(assetCard.getInventoryTask())) {
			//1.添加一条盘点任务明细资产表
			AssetInventoryTaskDetail assetInventoryTaskDetail = new AssetInventoryTaskDetail();
			assetInventoryTaskDetail.setTaskId(assetCard.getInventoryTask());
			assetInventoryTaskDetail.setDetailStatus(TaskDetailEnum.INVENTORY_PROFIT.getStatus());
			assetInventoryTaskDetail.setNowCardName(assetCard.getAssetName());
			assetInventoryTaskDetail.setCardId(assetCard.getCardId());
			assetInventoryTaskDetail.setId(assetInventoryTaskDetailService.createKey("id"));
			assetInventoryTaskDetailService.insert(assetInventoryTaskDetail);


		}
		//2.添加一条资产卡片操作记录表
		AssetCardOper assetCardOper = new AssetCardOper();
		BeanUtils.copyProperties(assetCard, assetCardOper);
		assetCardOper.setRequireId(assetCard.getInventoryTask());
		assetCardOper.setNowDeptid(assetCard.getDeptid());
		assetCardOper.setNowDeptName(assetCard.getDeptName());
		assetCardOper.setNowBranchId(assetCard.getBranchId());
		assetCardOper.setNowBranchName(assetCard.getBrandName());
		assetCardOper.setNowPsersonLiableUserid(assetCard.getPersonLiableUserid());
		assetCardOper.setNowPsersonLiableUsername(assetCard.getPersonLiableUsername());
		assetCardOper.setNowWarehouseId(assetCard.getWarehouseId());
		assetCardOper.setNowWarehouseName(assetCard.getWarehouseName());
		assetCardOper.setAllocDate(new Date());
		assetCardOper.setAssetStatusBefore("0");
		assetCardOper.setAssetStatusAfter(assetCard.getCardStatus());
		assetCardOper.setId(assetCardOperService.createKey("id"));
		assetCardOperService.insert(assetCardOper);

	}

	/**
	 * 修改资产卡片
	 * @param assetCard
	 */
	@Transactional
	public void updateAssetCard(AssetCard assetCard) {
		//1.资产编码是否存在
		AssetCard ac = new AssetCard();
		ac.setAssetSn(assetCard.getAssetSn());
//        if(this.countByWhere(ac)>0) {
//            throw new BizException("资产编码不能重复");
//        }

		User user = LoginUtils.getCurrentUserInfo();
		//1.修改数据
		assetCard.setLastEditUserid(user.getUserid());
		assetCard.setLastEditUsername(user.getUsername());
		assetCard.setLastEditTime(new Date());
		this.updateByPk(assetCard);
	}

	public List<Map<String, Object>> selectListMapByWhereAndCategory(Map<String, Object> assetCard) {
		if(!StringUtils.isEmpty(assetCard.get("assetStatusArr"))) {
			assetCard.put("assetStatusArr", assetCard.get("assetStatusArr").toString().split(","));
		}
		return baseMapper.selectListMapByWhereAndCategory(assetCard);
	}


	/**
	 * 查询可以盘点的资产
	 * @param assetCard
	 * @return
	 */
	public List<Map<String, Object>> getInventoryCards(Map<String, Object> assetCard) {
		return baseMapper.selectInventoryCards(assetCard);
	}

	/**
	 * 批量更新资产卡片
	 * @param assetCard
	 */
	public void batchEditAssetCard(Map<String, Object> assetCard) {
		baseMapper.batchUpdateCards(assetCard);
	}

	public void importAssetCard(MultipartFile file, AssetCardService assetCardService) throws IOException {
		//文件输入流
		InputStream in = file.getInputStream();
		//调用方法进行读取
		EasyExcel.read(in, AssetCardExcelVo.class, new AssetCardImportExcelListener(
				this,
				warehouseService,
				assetCategoryService,
				deptService,
				sysUserService)).sheet().doRead();
	}

	/**
	 * 批量添加数据通过导入的excel数据
	 * @param list
	 */
	public void batchSaveDataByExcel(List<AssetCardExcelVo> list) {
		User user = LoginUtils.getCurrentUserInfo();
		List<AssetCard> assetCards = new ArrayList<>();
		for (AssetCardExcelVo assetCardExcelVo : list) {
			AssetCard assetCard = new AssetCard();
			BeanUtils.copyProperties(assetCardExcelVo, assetCard);
			assetCard.setCreateTime(new Date());
			assetCard.setCreateUserid(user.getUserid());
			assetCard.setCreateUsername(user.getUsername());
			assetCard.setLastEditUserid(user.getUserid());
			assetCard.setLastEditUsername(user.getUsername());
			assetCard.setLastEditTime(new Date());
			assetCard.setCardId(this.createKey("cardId"));
			//是否正在盘点 0否 1是
			assetCard.setIsInventory("0");
			assetCard.setCardType(MngStatus.SUBMIT.getStatus());

			if(assetCard.getCardStatus().equals(AssetStatusEnum.LEAVEUNUSED.getDesc())) {
				assetCard.setCardStatus(AssetStatusEnum.LEAVEUNUSED.getStatus());
			}

			if(assetCard.getCardStatus().equals(AssetStatusEnum.ISUSE.getDesc())) {
				assetCard.setCardStatus(AssetStatusEnum.ISUSE.getStatus());
			}

			if(assetCard.getCardStatus().equals(AssetStatusEnum.MAINTAIN.getDesc())) {
				assetCard.setCardStatus(AssetStatusEnum.MAINTAIN.getStatus());
			}

			if(assetCard.getCardStatus().equals(AssetStatusEnum.BORRON.getDesc())) {
				assetCard.setCardStatus(AssetStatusEnum.BORRON.getStatus());
			}

			if(assetCard.getCardStatus().equals(AssetStatusEnum.SCRAP.getDesc())) {
				assetCard.setCardStatus(AssetStatusEnum.SCRAP.getStatus());
			}

			assetCards.add(assetCard);
		}
		this.batchInsert(assetCards);
	}

	public List<AssetCard> selectIsFlowingListByIds(List<String> cardIds) {
		return baseMapper.selectIsFlowingListByIds(cardIds);
	}

	public List<String> batchCreateAssetSn(String passetSn, String branchId,int inNum){
		AssetCard assetCardQ = new AssetCard();
		assetCardQ.setBranchId(branchId);
		assetCardQ.setPassetSn(passetSn);
		long num=this.countByWhere(assetCardQ);
		List<String> assetSnList=new ArrayList<>();
		long seq=num;
		for (int k = 0; k < inNum; k++) {
			String numStr=(seq+k+1)+"";
			int lenght=4-numStr.length();
			String suffix="";
			for (int i = 0; i < lenght; i++) {
				suffix=suffix+"0";
			}
			suffix=suffix+numStr;
			String assetSn=passetSn+suffix;
			assetSnList.add(assetSn);
		}

		return assetSnList;
	}

	public String createAssetSn(String passetSn, String branchId) {
		AssetCard assetCardQ = new AssetCard();
		assetCardQ.setBranchId(branchId);
		assetCardQ.setPassetSn(passetSn);
		long num=this.countByWhere(assetCardQ);
		String numStr=(num+1)+"";
		int lenght=4-numStr.length();
		String suffix="";
		for (int i = 0; i < lenght; i++) {
			suffix=suffix+"0";
		}
		suffix=suffix+numStr;
		String assetSn=passetSn+suffix;
		return assetSn;
	}

    public void batchUpdateAssetCardInventoryStatus(Map<String, Object> params) {
		baseMapper.batchUpdateAssetCardInventoryStatus(params);
    }

	public List<AssetDetail> selectAssetSnIsExit(List<String> queryParams) {
		return baseMapper.selectAssetSnIsExit(queryParams);
	}


	/** 请在此类添加自定义函数 */


}

